import './css/fade.scss';
import 'animate.css';
import Carousel from './Carousel';

class Fade extends Carousel {
  constructor(el, { defaultIndex, duration }) {
    super(el);
    this.duration = duration;
    this._index = defaultIndex;
    this.init();
  }

  // static timer = null;

  //通过定义并操作index可以实现轮播图的切换
  get currentIndex() {
    return this._index;
  }

  set currentIndex(val) {
    this.update(() => {
      this._index = val;
    });
  }

  init() {
    this.show();
    this.bindEvent();
    this.autoPlay();
  }

  handleMouseEnter() {
    clearInterval(this.timer);
  }

  handleMouseLeave() {
    this.autoPlay();
  }

  handleDotClick(e) {
    const tar = e.target;
    if (tar.className === 'dot') {
      //通过操作index可以实现轮播图的切换
      this.currentIndex = [].indexOf.call(this.$dots, tar);
    }
  }

  show() {
    const cls = ['animate__animated', 'animate__fadeIn', 'active'];
    this.$imgWraps[this.currentIndex].classList.add(...cls);
    this.$dots[this.currentIndex].classList.add('active');
  }

  hide() {
    const cls = [
      'animate__fadeIn',
      'animate__animated',
      'animate__fadeOut',
      'active'
    ];
    this.$imgWraps[this.currentIndex].classList.remove(...cls);
    this.$dots[this.currentIndex].classList.remove('active');
  }

  autoPlay() {
    this.timer = setInterval(() => {
      if (this.currentIndex >= this.$imgWraps.length - 1) {
        this.currentIndex = 0;
      } else {
        this.currentIndex++;
      }
    }, this.duration);
  }

  update(setIndex) {
    this.hide();
    setIndex();
    this.show();
  }
}

export default Fade;
